package com.sxj.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 石小俊
 */
public class Test07_多表保存操作 {

    public static void main(String[] args) {
        Dept dept = new Dept("研发部", "研发产品");
        // 保存部门,并返回自动生成的主键的值
        Integer id = insertReturnPrimaryKey(dept);
        System.out.println("提示:部门添加成功");

        // 保存员工
        Emp e1 = new Emp("admin", 8000.0, id);
        Emp e2 = new Emp("jack", 9000.0, id);
        Emp e3 = new Emp("lucy", 8500.0, id);
        insertEmp(e1);
        insertEmp(e2);
        insertEmp(e3);
        System.out.println("提示:员工全部添加成功");
    }


    public static Integer insertReturnPrimaryKey(Dept dept) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_dept(name,remark) ")
                    .append(" values(?,?)")
                    .toString();
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, dept.getName());
            ps.setString(2, dept.getRemark());
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            while (rs.next()) {
                id = rs.getInt(1);
            }
            return id;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }

    public static void insertEmp(Emp emp) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp(name,salary,dept_id) ")
                    .append(" values(?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, emp.getName());
            ps.setDouble(2, emp.getSalary());
            ps.setInt(3, emp.getDeptId());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

}
